#include "cash.h"

CASH::CASH(QObject *parent, QString path) :QObject(parent)
{

    cash_pixmap = new QHash <QString,QPixmap*> ();
    cash_mng = new QHash <QString,QMovie*> ();
    cash_poly = new QHash <QString,QPainterPath*> ();
    cash_ogg = new QHash <QString,MediaObject*> ();

    Loading(path);

}

void CASH::Loading(QString path)
{

    Find_File(path);

    foreach(QString a,all_files){                                           // Всё что берём из кэша разыменовать!!!

        QString key(a.replace(QApplication::applicationDirPath()+"/",""));

        if( a.endsWith(".png") )
            cash_pixmap->insert(key,new QPixmap(a));

        if( a.endsWith(".svg") )
            cash_pixmap->insert(key,new QPixmap(a));

        if( a.endsWith(".poly") )
            cash_poly->insert(key,Load_Shape(a));

        if( a.endsWith(".mng") )
            cash_mng->insert(key,new QMovie(a));

        if( a.endsWith(".ogg") ){
            MediaObject *m = createPlayer(GameCategory,MediaSource(a));
            cash_ogg->insert(key,m);
        }

    }

}

QPainterPath *CASH::Load_Shape(QString file_name) const
{

    QFile *file = new QFile(file_name);
    file->open(QIODevice::ReadWrite);


    QString *data = new QString(file->readAll());
    QPolygon *poly = new QPolygon();

    QStringList lst = data->split("*");

    lst.removeLast();

    while(!lst.isEmpty()){
        QPoint p(lst.at(0).toInt(), lst.at(1).toInt());
        poly->append(p);
        lst.removeFirst();
        lst.removeFirst();
    }

    file->close();

    QPainterPath *ready = new QPainterPath();
    ready->addPolygon(*poly);

    return ready;

}

CASH::~CASH()
{

}

void CASH::Find_File(QString dir)                                   // Рекурсивный поиск файлов...
{

    QDir d( dir);

    foreach( QFileInfo fi, d.entryInfoList()){

         QString szFileName = fi.absoluteFilePath();

         if( fi.isDir()){

            if( fi.fileName()=="." || fi.fileName()=="..")
                continue;

                Find_File( szFileName);

         }

         if( fi.isFile() )
             all_files<<fi.absoluteFilePath();


     }

}
